<template>
  <div class="taskList" v-loading="taskloading">
    <div class="allTask" >
      <!-- 应急任务列表 -->
      <div class="title taskOperation">救援任务列表({{newTasks.length}}个)</div>
      <!-- <div class="taskOperation"></div> -->
      <div class="allTaskList">
        <div class="bg">
          <TaskCard
            @click.native="selectTask(newTasks.indexOf(item))"
            v-for="item in newTasks"
            :key="item.index"
            :index="newTasks.indexOf(item)"
            :taskId="item.taskId"
            :taskType="item.taskType"
            :position="[item.longitude, item.latitude]"
            :peopleNum="item.requestNum"
            :describe="item.taskDescription"
            :selectCard="selectCardIndex"
            @selectRescue="openDialog"
            @deleteCallBack="deleteCallBack"
          ></TaskCard>
        </div>
      </div>
    </div>
    <div class="map" id="container">
      <div class="info" id="text" v-if="selectEvent != null">
        应急请求卡片
        <div>编号：{{ selectEvent.requestId }}</div>
        <div>描述：{{ selectEvent.requestDescription }}</div>
        <div>位置：{{ [selectEvent.longitude, selectEvent.latitude] }}</div>
      </div>
    </div>

    
    <div class="wordsContainer" ref="shrink">
         <div class="shrinkBox" @click="hideChattingBox">
            <i v-bind:class="[hideFlag ? 'el-icon-arrow-left' : 'el-icon-arrow-right']" style="margin-top:10px"></i>
         </div>
         <div class="chatBox" id="chatBox" >
            <!-- <div  style="width:100%"> -->
              <div class="msgBox" v-for="item in messageList" :key="item.index">
                <div class="time">{{item.messageTime | formatDateTime }}</div>
                <div  class="msgContainer otherMsg " :class="{myMsg:item.direction==1 }">
                {{item.description}}
                </div>
              </div>  
            <!-- </div> -->
          </div>
         
         <div class="sendInput">
          <el-input
            type="textarea"
            :rows="4"
            placeholder="编辑留言消息"
            v-model="chattingMsg">
          </el-input>
          <el-button type="primary" plain @click="sendChatting" size="small" >发送</el-button>
         </div>
    </div>

    <el-dialog
      :title="'任务:' + taskName"
      :visible.sync="dialogVisible"
      width="40%"
      top="18vh"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
    <div>
      <el-select v-model="selectRescueGroups" multiple placeholder="请选择">
        <el-option
          v-for="item in rescueGroups"
          :key="item.id"
          :label="item.teamName"
          :value="item.id"
        >
        </el-option>
      </el-select>
    </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="determine">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import "../css/TaskList.css";
import TaskCard from "@/components/TaskCard.vue";
import { NODE_ENV } from "../../config/prod.env";
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
import websocketFeature from "@/utils/webSocket";
import { formatFunc ,formatFunc2} from "../utils/utils";


export default {
  data() {
    return {
      webSocket1:null,
      webSocketFlag:false,
      chattingMsg:"",   //聊天框数据
      hideFlag:true,   //聊天框是否隐藏
      messageList:[],

      rescueGroups:[
        // {value:1,label:"蓝天救援队"},
        // {value:2,label:"粉天救援队"},
        // {value:3,label:"黄天救援队"},
        // {value:4,label:"红天救援队"},
        // {value:5,label:"绿天救援队"},
        // {value:6,label:"白天救援队"},
      ],
      selectRescueGroups:[],
      selectCardIndex: 0, //当前选择任务的index
      selectEvent: null,  //点击标记点的事件
      selectRescue:null,
      map: null,
      newTasks: [],
      theEvents: [],   //考虑theevents只存事件数组，不存所有任务，毕竟清除任务时，index可能会变化
      theRescues:[],
      mapMarkers: [],  //存在的意义在于，找到标记点的index
      rescueMarkers:[],
      center: "",
      taskName: "",
      dialogVisible: false,
      taskloading:true
    };
  },
  computed: {},
  
  beforeDestroy:function(){
    //websocketFeature.remove(this.webSocket1,"")
  },
  mounted: function () {
      //  var newMsg=JSON.parse('{"control":"0101","from":"flood:7","to":"manager:0","content":"好难受","messageTime":"2022-06-28T10:08:14.000+00:00","taskId":"1","taskType":"flood"}')
      //  console.log(newMsg.from.split(":")[1]);
    //绘地图
    AMapLoader.load({
      key: "3be1ca4ff35ba5046d0c188a12e4fae7", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Scale", "AMap.ToolBar"], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      AMapUI: {
        // 是否加载 AMapUI，缺省不加载
        version: "1.1", // AMapUI 版本
        plugins: ["overlay/SimpleMarker"], // 需要加载的 AMapUI ui插件
      },
    })
      .then((AMap) => {
        this.map = new AMap.Map("container", {
          //设置地图容器id
          viewMode: "3D", //是否为3D地图模式，矢量地图
          zoom: 12, //初始化地图级别
          center: [114.302725, 30.556636], //初始化地图中心点位置,经纬度
        });
        this.map.addControl(new AMap.Scale());
        this.map.addControl(new AMap.ToolBar());
        this.map.on("mapmove", this.getcenter);
        // this.map.add(new AMap.Marker({
        // position:this.map.getCenter()
        // }));
        //先显示地图之后再请求数据
        axios.get('/getAllTasks').then((resp) => {
          if (resp.status == 200) {
            // this.newTasks = resp.data
            for(var e in resp.data){
              if(resp.data[e][0].length!=0){
                var events=resp.data[e][0].reverse()
                this.newTasks.push.apply(this.newTasks,events)
              }
              console.log(this.newTasks);
            }
            // console.log(this.newTasks);
            for (var i = 0; i < this.newTasks.length; i++) {
              this.theEvents.push([]);
              this.theRescues.push([])
              //有几个任务，push几个位置
            }
            //字段：taskId，taskDescription，
            //startTime,latitude,longitude,taskRange
            // console.log(this.theEvents);
            if(this.newTasks.length!=0){
              this.getEventOfTask();
              this.getRescueOFTask();
            }
            // this.map.setFitView(); //自适应调整地图，使其包含所有点
            this.taskloading=false
            if(this.webSocket1==null&&!this.webSocketFlag){
              this.webSocket1 = websocketFeature.create(
                'ws://1.15.130.134:7080/websocket/groupChat/sendMessage',
                this.webSocket1CallBack.bind(this)
              );
              this.webSocketFlag=true
            }
          }
        });
      })
      .catch((e) => {
        console.log(e);
      });

  },
  components: { TaskCard: TaskCard },
  methods: {
    //获取消息的回调函数
    webSocket1CallBack(e){
       console.log(e.data);
       var newMsg=JSON.parse(e.data)
       console.log(JSON.parse(e.data));
       //如果是私信标志
       if(newMsg.control="0101"){
          console.log(newMsg.from.split(":")[1]);
          if(this.selectRescue==null&&newMsg.from.split(":")[1]==this.selectEvent.requestId){
            //求救者消息
            var formatMsg={
              messageTime:newMsg.messageTime,
              direction:newMsg.from.match(/manager/g)=="manager"?1:0,
              description:newMsg.content
            }
            console.log(formatMsg);
            this.messageList.push(formatMsg)
            this.moveScollBar()
          }else if(this.selectRescue!=null&&newMsg.from.split(":")[1]==this.selectRescue.id){
             //救援队消息
             var formatMsg={
              messageTime:newMsg.messageTime,
              direction:newMsg.from.match(/manager/g)=="manager"?1:0,
              description:newMsg.content
            }
            console.log(formatMsg);
            this.messageList.push(formatMsg)
            this.moveScollBar()
          }else{
            this.$message({
              message: '您收到了一条消息！',
              });
          }
       }
    },
    //聊天框一直位于底部
    moveScollBar(){
      setTimeout(function(){
        document.getElementById("chatBox").scrollTop = document.getElementById("chatBox").scrollHeight;
      },10);
    },
    //点击标记调用改变messageList，重新渲染消息列表
    getMessages(){
      //axios请求
      if(this.selectEvent!=null){
       axios.get('/request/getMessagesBefore?teamType=flood&teamId='+this.selectEvent.requestId+'&dropTime='+formatFunc(new Date())+'&taskId='+this.newTasks[this.selectCardIndex].taskId).then((resp) => {
          if (resp.status == 200) {
            console.log(resp.data);
            this.messageList=[]
            this.messageList=resp.data
            this.moveScollBar()
          }
        })
      }else{
        axios.get('/request/getMessagesBefore?teamType=rescueTeam&teamId='+this.selectRescue.id+'&dropTime='+formatFunc(new Date())+'&taskId='+this.newTasks[this.selectCardIndex].taskId).then((resp) => {
          if (resp.status == 200) {
            console.log(resp.data);
            this.messageList=[]
            this.messageList=resp.data
            this.moveScollBar()
          }
        })
      }
      this.$refs.shrink.style.right="-20px";
      this.hideFlag=false;
    },
    //聊天框隐藏和显示
    hideChattingBox(){
      if(this.hideFlag){
        this.$refs.shrink.style.right="-20px";
        this.hideFlag=false;}
      else{
        this.$refs.shrink.style.right="-300px"
        this.hideFlag=true;
        }
    },
    //websocket发送消息
    sendChatting(){
      //websocket连接发送消息
      if(this.chattingMsg!=""){
        console.log(this.selectEvent);
        var myNewMsg={messageTime:new Date(),direction:1,description:this.chattingMsg}
        console.log(formatFunc(myNewMsg.messageTime));
        if(this.selectEvent != null){
          var transferMsg='{"control":"0101","from":"manager:4","to":"flood:'+this.selectEvent.requestId+'","content":"'+this.chattingMsg+'","messageTime":"'+formatFunc2(myNewMsg.messageTime)+'","taskId":"'+this.newTasks[this.selectCardIndex].taskId+'","taskType":"flood"}'
        }else{
          var transferMsg='{"control":"0101","from":"manager:4","to":"rescueTeam:'+this.selectRescue.id+'","content":"'+this.chattingMsg+'","messageTime":"'+formatFunc2(myNewMsg.messageTime)+'","taskId":"'+this.newTasks[this.selectCardIndex].taskId+'","taskType":"flood"}'
        }
        // console.log(this.webSocket1);
        websocketFeature.send(this.webSocket1,transferMsg)
        this.messageList.push(myNewMsg)
        this.chattingMsg=""
        this.moveScollBar()
      }else{
        this.$message({
        message: "消息不能为空",
        type: 'warning'
        });
        this.closeDialog()
      }
      // console.log(height);
      // this.$refs.chatBox.scroll({ top: 600 , left: 0, behavior: 'smooth'})
    },
    //分配救援队
    determine(){  
      console.log(this.selectRescueGroups);
      var count=0
      this.selectRescueGroups.forEach(element => {
        axios.get('/team/allcoTaskToTeam?teamType=rescueTeam&teamId='+element+'&taskType='+this.newTasks[this.selectCardIndex].type+'&taskId='+this.newTasks[this.selectCardIndex].taskId).then((resp)=>{
        // this.rescueGroups=resp.data
            console.log("a"+resp.data);
            count=count+1
            console.log(count);
            if(count>=this.selectRescueGroups.length){
              this.$message({
              message: "分配成功",
              type: 'success'
              });
              this.dialogVisible=false
            }
          }).catch((error)=>{
          this.$message({
              message: error,
              type: 'warning'
              });
          });
      });
    },
    getcenter() {
      this.center = this.map.getCenter().toString();
    },
    //打开选择救援队弹窗
    openDialog(taskName,taskId) {
      //获取相关救援队列表
      this.selectRescueGroups=[]
      this.taskName = taskName
      // console.log(this.taskName);
      // console.log(taskId);
      console.log(this.newTasks[this.selectCardIndex].type);
      axios.get('/team/getTeamByTask?teamType=rescueTeam&taskId='+taskId+'&taskType='+this.newTasks[this.selectCardIndex].type).then((resp)=>{
        this.rescueGroups=resp.data[0]
        console.log(this.rescueGroups);
        this.dialogVisible = true;
      }).catch((error)=>{
          this.$message({
              message: error,
              type: 'warning'
              });
      });
      
    },
    //在删除任务之后的回调函数
    deleteCallBack(){    
      //1.重新请求任务列表
      //2.清空theevents
      //3.置selectCardIndex=0
      console.log("回调函数");
       this.newTasks=[]
       axios.get('/getAllTasks').then((resp) => {
          if (resp.status == 200) {
            for(var e in resp.data){
              if(resp.data[e][0].length!=0){
                this.newTasks.push.apply(this.newTasks,resp.data[e][0])
              }
              console.log(this.newTasks);
            }
            this.theEvents=[]
            this.theRescues=[]
            for (var i = 0; i < this.newTasks.length; i++) {
              this.theEvents.push([]);
              this.theRescues.push([])
              //有几个任务，push几个位置
            }
            this.selectCardIndex=0
            this.getEventOfTask();
            this.getRescueOFTask();
          }})
    },
    //得到某一个任务的所有请求，并展示标记点
    getEventOfTask() {
      axios.get('/getTask/getRequesteds?type='+this.newTasks[this.selectCardIndex].type+'&taskId='+this.newTasks[this.selectCardIndex].taskId).then((resp) => {
        if (resp.status == 200) {
          this.theEvents[this.selectCardIndex] = resp.data;
          //字段：taskId，taskDescription，
          //startTime,latitude,longitude,taskRange
          // console.log(this.theEvents);
          console.log(this.theEvents);
          this.mapMarkers = [];
          var _this = this; //创建指针喽
          AMapUI.loadUI(["overlay/SimpleMarker"], function (SimpleMarker) {
            _this.theEvents[_this.selectCardIndex].forEach((element) => {
              var marker = new SimpleMarker({
                
                iconTheme: "numv1",
                //背景图标样式
                iconStyle: "red", //红色代表求救者，蓝色代表救援队
                map: _this.map, //直接设置地图
                position: [element.longitude, element.latitude],
              });
               _this.mapMarkers.push(marker);
              marker.on("click", _this.showMarkerInfo);
            });
            // _this.theTeams[_this.selectCardIndex].forEach((element) => {
            //   var marker = new SimpleMarker({
            //     iconTheme: "numv1",
            //     //背景图标样式
            //     iconStyle: "blue", //红色代表求救者，蓝色代表救援队
            //     map: _this.map, //直接设置地图
            //     position: [element.longitude, element.latitude],
            //   });
            //   _this.mapMarkers.push(marker);
            //   marker.on("click", _this.showMarkerInfo);
            // });

            //救援队需要另外的点标记数组和新的点击函数
            _this.map.setFitView(); //自适应调整地图，使其包含所有点
          });
        }
      });
    },
    getRescueOFTask(){
      axios.get('/getTeamsInATask?taskId='+this.newTasks[this.selectCardIndex].taskId+'&taskType='+this.newTasks[this.selectCardIndex].type).then((resp) => {
              if (resp.status == 200) {
                this.theRescues[this.selectCardIndex] = resp.data;
                if(this.theRescues[this.selectCardIndex]==[]){return}
                //字段：
                console.log(this.theRescues);
                this.rescueMarkers = [];
                var _this = this; //创建指针喽
                AMapUI.loadUI(["overlay/SimpleMarker"], function (SimpleMarker) {
                  _this.theRescues[_this.selectCardIndex].forEach((element) => {
                    var marker = new SimpleMarker({
                      iconTheme: "numv1",
                      //背景图标样式
                      iconStyle: "blue", //红色代表求救者，蓝色代表救援队
                      map: _this.map, //直接设置地图
                      position: [element.longitude, element.latitude],
                    });
                     _this.rescueMarkers.push(marker);
                    marker.on("click", _this.showMarkerInfoR);
                  });
                  //救援队需要另外的点标记数组和新的点击函数
                  _this.map.setFitView(); //自适应调整地图，使其包含所有点
                });
              }
            });
    },
    //点击标记点显示详情信息，更新消息列表
    showMarkerInfo(e) {
      console.log(e.target);
      this.selectRescue=null;  //救援队和事件互斥点击
      this.selectEvent =this.theEvents[this.selectCardIndex][this.mapMarkers.indexOf(e.target)];
      console.log(this.selectEvent);
      this.getMessages()
      // console.log(this.selectEvent);
    },
    showMarkerInfoR(e) {
      console.log(e.target);
      this.selectEvent=null;  //救援队和事件互斥点击
      this.selectRescue =this.theRescues[this.selectCardIndex][this.rescueMarkers.indexOf(e.target)];
      console.log(this.selectRescue);
      this.getMessages()
      // console.log(this.selectEvent);
    },
    //点击任务，切换请求
    selectTask(id) {
      //第二次之后阻止冒泡，优化性能
      if(this.selectCardIndex!=id){
          this.selectCardIndex = id;
          // console.log(this.selectCardIndex);
          this.map.clearMap(); 
          this.getEventOfTask();
          this.getRescueOFTask();
          // this.map.setFitView(); //自适应调整地图，使其包含所有点
      }
    },
    //关闭弹窗的提示
    handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            this.dialogVisible=false
            done();
          })
          .catch(_ => {});
      },
  },
  //   emits: ["deleteEvent"],
  //   props:["index","status","eventType","phone","position","describe"]
};
</script>



// newTasks:[{index:0,status:1,taskType:"洪水",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsna"},
//            {index:1,status:1,taskType:"地震",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaa"},
//            {index:2,status:1,taskType:"户外",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaaaaaaaaaa"},
//            {index:3,status:1,taskType:"其他",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaaaaaaaaaa"},
//            {index:4,status:1,taskType:"火灾",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaaaaaaaaaa能看到这立马我是最长的了啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊"},
//            {index:5,status:1,taskType:"洪水",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaaaaaaaaaa能看到这立马"},
//            {index:6,status:1,taskType:"洪水",position:"xxx市xx区xx地",peopleNum:"15人",describe:"aqwertyuipasjdklzmxncbzgsnabsnaaaaaaaaaaaaaaa能看到这立马"}],

// positions:[[[114.30,30.56],[114.25,30.53],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.31,30.55],[114.24,30.54],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.32,30.54],[114.23,30.55],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.33,30.53],[114.22,30.56],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.34,30.52],[114.21,30.57],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.35,30.51],[114.20,30.58],[114.2,30.2],[114.4,30.6],[114.4,30.52]],
//            [[114.36,30.50],[114.20,30.59],[114.2,30.2],[114.4,30.6],[114.4,30.52]]], //暂时失业

 AMapLoader.load({
            // key:"3be1ca4ff35ba5046d0c188a12e4fae7",    // 申请好的Web端开发者Key，首次调用 load 时必填
            // version:"2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            // plugins:[''],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
        }).then((AMap)=>{
            //清除上一个任务的点标记
            // this.mapMarkers.forEach(element=>{
            //     this.map.remove(element);
            // })
            // 清除地图上所有添加的覆盖物
            this.map.clearMap();
            //点标记组置空
            this.mapMarkers=[];
            var _this=this //创建指针喽
            AMapUI.loadUI(['overlay/SimpleMarker'], function(SimpleMarker) {
            _this.positions[id].forEach(element => {
                // var marker = new AMap.Marker({
                //     position:element,   // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                //     icon:"//vdata.amap.com/icons/b18/1/2.png",
                // // title: '北京'
                // });
            var marker=new SimpleMarker({
                //前景文字
                //iconLabel: 'A',  //可以选中时添加一个标记
                iconTheme: 'numv1',
                //背景图标样式
                iconStyle: 'red',   //红色代表求救者，蓝色代表救援队
                map: _this.map,    //直接设置地图
                position: element
            });
            // 将创建的点标记添加到已有的地图实例：
                // this.map.add(marker);
                _this.mapMarkers.push(marker);
            });
            // console.log(this.mapMarkers);
            _this.map.setFitView(_this.mapMarkers); //自适应调整地图，使其包含所有点
            })
        }).catch(e=>{
            console.log(e);
        })
        {msgData:"请问你需要帮助嘛？我这边可以帮你联系噢",otherMsg:false},
                   {msgData:"这边雨好大，水好深",otherMsg:true},
                   {msgData:"请问你需要帮助嘛？我这边可以帮你联系噢",otherMsg:false},
                   {msgData:"有吃的吗，我好饿",otherMsg:true},
                   {msgData:"请问你需要帮助嘛？我这边可以帮你联系噢",otherMsg:false},
                   {msgData:"在水里泡久了，我好像发烧了",otherMsg:true}

                    <!-- <div class="msgContainer myMsg" :class="{otherMsg:otherMsg }">aaaaaaaaaaabbbbccc你好遇到什么困难了嘛？需要什么帮助嘛？</div>
            <div class="msgContainer myMsg" :class="{otherMsg:otherMsg }">aaaaaaaaaaabbbbccc你好遇到什么困难了嘛？需要什么帮助嘛？</div>
            <div class="msgContainer myMsg" :class="{otherMsg:otherMsg }">aaaaaaaaaaabbbbccc你好遇到什么困难了嘛？需要什么帮助嘛？</div>
            <div class="msgContainer myMsg" :class="{otherMsg:otherMsg }">aaaaaaaaaaabbbbccc你好遇到什么困难了嘛？需要什么帮助嘛？</div>
            <div class="msgContainer myMsg" :class="{otherMsg:otherMsg }">aaaaaaaaaaabbbbccc你好遇到什么困难了嘛？需要什么帮助嘛？</div> -->